const { User } = require("../model");
const { sign } = require("../util/jwt");
const { jwtSecret } = require("../config/config.default");

// 用户注册
exports.register = async (req, res, next) => {
  try {
    let user = new User(req.body.user);
    await user.save();
    user = user.toJSON();
    delete user.password;
    res.status(201).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};

// 用户登录
exports.login = async (req, res, next) => {
  try {
    let user = req.user.toJSON();
    delete user.password;
    const token = await sign({ userId: user._id }, jwtSecret, {
      expiresIn: "1 day", // 默认30s过期
    });
    user.token = token;
    res.status(200).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};

// 获取当前登录用户
exports.getCurrentUser = async (req, res, next) => {
  try {
    res.status(200).json({
      user: req.user,
    });
  } catch (error) {
    next(error);
  }
};

// 更新用户
exports.updateUser = async (req, res, next) => {
  try {
    let user = req.user;
    await User.findByIdAndUpdate(user._id, req.body.user);
    user = await User.findById(user._id);
    res.status(200).json({
      user,
    });
  } catch (error) {
    next(error);
  }
};
